const state = {
    urlArray: [],
    activeUrl: null,
};
const getters = {};
const mutations = {};
const actions = {
    setActiveUrl(context, urlObj) {
        context.state.activeUrl = urlObj;
    },
    checkUrl(context) {
        if (!context.state.activeUrl) {
            return
        };
        var urlId = context.state.activeUrl.urlId;
        var ishave = false;
        for (let i = 0; i < context.state.urlArray.length; i++) {
            const element = context.state.urlArray[i];
            if (element.urlId == urlId) {
                ishave = true;
                break;
            };
        };
        if (!ishave) {
            context.state.activeUrl = null;
        };
    },
    getRenderData(context) {
        // action=> 获取全部URl
        window.action.url.getAll().then((res) => {
            if (res) {
                for (let i = 0; i < res.length; i++) {
                    const element = res[i];
                    element.ping = '';
                    element.loading = false;
                    element.close = false;
                };
                context.state.urlArray = res;
                context.dispatch('checkUrl');
            };
        });
    },
    creatUrl(context, param) {
        // action=> 创建URL
        window.action.url.creat(param).then((res) => {
            if (res) {
                context.dispatch('getRenderData');
            };
        });
    },
    updateUrl(context, param) {
        // action=> 更新Url
        window.action.url.updata(param).then((res) => {
            if (res) {
                for (let i = 0; i < context.state.urlArray.length; i++) {
                    const element = context.state.urlArray[i];
                    if (element.urlId == param.id) {
                        element.title = param.title;
                        element.str = param.str;
                        element.type = param.type;
                        element.port = param.port;
                        break;
                    };
                };
            };
        });
    },
    deleteUrl(context, id) {
        // action=> 删除URL
        window.action.url.delete(id).then((res) => {
            if (res) {
                context.dispatch('getRenderData');
            };
        });
    },
};

export default {
    namespaced: true,
    state,
    getters,
    mutations,
    actions
}